#include"weatherTool.h"

//初始化
QMap<QString,QString>weatherTool::mCityMap{};

QString weatherTool::getCityCode(QString cityName)
{
    if(mCityMap.isEmpty())
    {
        initCityMap();
    }

    mCityMap.find(cityName);
    QMap<QString,QString>::iterator it=mCityMap.find(cityName);

    if(it==mCityMap.end())
    {
        it=mCityMap.find(cityName+"市");
    }

    if(it!=mCityMap.end())
    {
        return it.value();
    }
    return "";
}


void weatherTool::initCityMap()
{
    QString filePath="D:/QT/LiarWeather/weather_citylist.json";
    QFile file(filePath);
    file.open(QIODevice::ReadOnly|QIODevice::Text);
    QByteArray josnCityCode=file.readAll();
    file.close();
    QJsonParseError CityCodeErr;
    QJsonDocument CityCodeDoc=QJsonDocument::fromJson(josnCityCode,&CityCodeErr);
    if(CityCodeErr.error!=QJsonParseError::NoError)
    {
        return;
    }

    if(!CityCodeDoc.isArray())
    {
        return;
    }

    QJsonArray cities=CityCodeDoc.array();
    for(int i=0;i<cities.size();i++)
    {
       QString mCityName=cities[i].toObject().value("cityName").toString();
       QString mCityCode=cities[i].toObject().value("cityCode").toString();

       if(mCityCode.size()>0)
       {
           mCityMap.insert(mCityName,mCityCode);
       }
    }

}

